import React from "react";
import { Text, View } from "@tarojs/components";
import { NavBar, Image, Icon, Field, CellGroup, Row, Col, PullToRefresh, VirtualList, InfiniteScroll, Tag, Button } from "@antmjs/vantui";
import { useState, useEffect,useRef } from "react";
import { CusSroll } from '../../../../components'
import { appSearch } from "../../../../https/home";
import "./index.scss"
import Taro,{getMenuButtonBoundingClientRect} from "@tarojs/taro";
import { HOST,diffTime} from "../../../../utils/const";

const pla = { android: "安卓", ios: "苹果", windows: "windows", mac: 'mac' }

const SearchPage = () => {
    const btn = getMenuButtonBoundingClientRect();
    const [hotSearchData, setHotSearchData] = useState(['音乐','影视','听书','定位','剪辑','拍照'])
    const [hotApp, setHotapp] = useState([])
    const [historyData, setHistoryData] = useState([])
    const [value, setValue] = useState(null)
    const [isSearch, setIsSearch] = useState(false)
    const [data, setData] = useState([]);
    const infiniteScrollRef = useRef();
    const virtualListRef = useRef();
    const [listData,setListData] = useState([])

    useEffect(() => {
        if (Taro.getStorageSync("searchHistory")) {
            setHistoryData(JSON.parse(Taro.getStorageSync("searchHistory")));
        }
    }, []);

    const searchAPP = () => {
        Taro.showLoading({title:"加载中"})
        appSearch({words:value}).then((res)=>{
           Taro.hideLoading()
           if(res.success){
            setListData(res?.data||[])
            setIsSearch(true)
            let array = [];
            if (Taro.getStorageSync("searchHistory")) {
                array = JSON.parse(Taro.getStorageSync("searchHistory"));
                array = array.filter((sItem)=>sItem!=value)
                array.unshift(value);
                Taro.setStorage({
                    key: "searchHistory",
                    data: JSON.stringify(array),
                });
                setHistoryData(array)
            } else {
                let itemData = [value];
                Taro.setStorage({
                    key: "searchHistory",
                    data: JSON.stringify(itemData),
                });
                setHistoryData(itemData)
            }
           }
        }) 
    }

    const navView = () => {
        return (
            <View className="search-view">
                <View style={{ width: value ? '55%' : '66%' }}>
                    <Field value={value} focus autoFocus placeholder='请输入关键词' style={{ fontSize: 12 }} onChange={(e) => setValue(e.detail)} />
                </View>
                {value ? <Icon onClick={() => {
                    setIsSearch(false)
                    setValue(null)
                    setListData([])
                }} name='cross' size={45} style={{ width: '12%' }} color="#8D949D" /> : null}
                <Icon onClick={searchAPP} name='search' size={45} style={{ width: '12%' }} color="#8D949D" />
            </View>
        )
    }

    return (
        <View className="home-view">
            <NavBar
                title={navView()}
                onClickLeft={() => Taro.navigateBack()}
                leftArrow
                fixed
            />
            {isSearch ? <PullToRefresh>
                <VirtualList
                    style={{ padding: 10, boxSizing: 'border-box',paddingTop:btn.bottom+20 }}
                    // height="calc(100vh - 135px)"
                    dataSource={listData}
                    ref={virtualListRef}
                    ItemRender={({ item,index }) => {
                        return (
                            <View  className='app-list-bg-view' style={{marginBottom:index==listData.length-1?30:0}}
                                onClick={()=>Taro.navigateTo({ url: `/pages/home/components/app_detail/index?id=${item.id}&version=${item.version}` })}>
                                <View className='img'>
                                    <Image src= {item?.icon?HOST+item?.icon:'https://img.yzcdn.cn/vant/cat.jpeg'} radius={'8%'} width={120} height={120} />
                                </View>
                                <View className='info-text'>
                                    <View>
                                         {item?.name}
                                    </View>
                                    <View className='tag-view'>
                                        {item?.core&&<>
                                        <Icon name="star" color="#13b858" size={40} />
                                        <Text className="star-text">{item?.core||''}</Text></>}
                                        <View className='version-view'>{item?.version}</View>
                                        <View className='version-view'>{item?.create_time ? diffTime(new Date(item?.create_time).getTime()) : '未知'}</View>
                                    </View>
                                    <View className='tag-view'>
                                        <Tag className='tag' type="primary">{item?.platform ? pla[item.platform] : ''}</Tag>
                                        <View className='version-view'>{item?.size}</View>
                                        {item?.downloadCnt&&<View className='separate-veiw'>·</View>}
                                        <View className='version-view'>{item?.downloadCnt||''}</View>
                                    </View>
                                </View>
                                <View className='time-view'>
                                    <Button onClick={()=>Taro.navigateTo({ url:`/pages/home/components/down_load_file/index?link=${item?.link}` })} className='btn' type='primary' size='mini'>下载</Button>
                                </View>
                            </View>
                        );
                    }}
                />
            </PullToRefresh> : <>
                {historyData.length > 0 && <View className="list-bg-view" style={{paddingTop:btn.bottom}}>
                    <View className="header-view">
                        <View>搜索记录</View>
                        <View onClick={() => {
                            Taro.removeStorage({ key: "searchHistory" })
                            setHistoryData([])
                        }}>清除</View>
                    </View>
                    <Row className="dark">
                        {historyData.map((item) => {
                            return (
                                <Col onClick={() => {
                                    setValue(item)
                                    setIsSearch(true)
                                }} span={8}>
                                    <View className="search-list-view">
                                        {item}
                                    </View>
                                </Col>
                            )
                        })}
                    </Row>
                </View>}
                <View className="list-bg-view"
                 style={{paddingTop:!isSearch&&historyData.length<=0?btn.bottom:0}}
                >
                    <View>热门搜索</View>
                    <Row className="dark">
                        {hotSearchData.map((item) => {
                            return (
                                <Col onClick={() => {
                                    setValue(item)
                                    setIsSearch(true)
                                    // Taro.navigateTo({ url: '/pages/home/components/app_version_list/index' })
                                }} span={8}>
                                    <View className="search-list-view">
                                        {item}
                                    </View>
                                </Col>
                            )
                        })}
                    </Row>
                </View>
                {/* <View className="list-bg-view">
                    <View>热门应用</View>
                    <View style={{ marginTop: 20 }}>
                        <CusSroll 
                          onClick={() => Taro.navigateTo({ url: '/pages/home/components/app_version_list/index' })} 
                          type={'search-app'} scrollWidth={80} 
                        />
                    </View>
                </View> */}
                </>}
        </View>
    )
}

export default SearchPage